<template>
    <div>
        <el-upload
            class="upload-demo"
            v-bind="$attrs"
            :http-request="uploadFile"
            ref="upload"
            :on-exceed="props['onExceed'] ?? handleExceed"
        >
            <slot></slot>
        </el-upload>
    </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage } from "element-plus";
import type { UploadInstance, UploadProps } from "element-plus";
import { reqUpload } from "@/api/file";
import getFileHash from "@/utils/tools/getFileHash.ts";

interface componentsProps {
    onExceed?: UploadProps["onExceed"];
}
const props = defineProps<componentsProps>();
// 获取实例
const upload = ref<UploadInstance>();
// 超出文件限制时记得提醒
const handleExceed: UploadProps["onExceed"] = () => {
    ElMessage.error("文件数量超出限制了，请删除后再进行上传");
};
// 上传文件
const uploadFile = async (options: any) => {
    const formData = await getFormData(options.file);
    const result = await reqUpload(formData);
    if (result.code === 200) {
        ElMessage.success("上传资源成功");
    } else {
        ElMessage.error("上传资源失败");
    }
    return result.data;
};

// 对文件进行处理
const getFormData = async (file: File): Promise<FormData> => {
    // 获取文件名字
    const file_name = file.name;
    // 获取文件后缀名
    const ext = file_name.split(".").pop();
    // 获取文件hash
    const hash = await getFileHash(file);
    // 生成唯一key
    const key = "id-" + Math.random().toString(36).substring(2, 11);

    // 整理数据
    const formData = new FormData();
    formData.append("key", key);
    formData.append("hash", hash);
    formData.append("ext", ext as string);
    formData.append("file", file);
    formData.append("file_name", file_name);
    return formData;
};
</script>

<style lang="scss" scoped></style>
